package com.sjh.lib_app.router.interceptor

import android.content.Context
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.sjh.baseutils.loge
import com.sjh.lib_app.event.LoginFailEvent
import com.sjh.lib_app.event.LoginSuccessEvent
import com.sjh.lib_app.login.LoginServiceWrap
import com.sjh.lib_app.router.RouteExtras
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * 检查登录的拦截器
 * @author Extends
 * @date 2020/6/12
 */
@Interceptor(priority = Int.MAX_VALUE, name = "检查登录的拦截器")
class LoginInterceptor : IInterceptor {

    private var p : Postcard? = null
    private var c : InterceptorCallback? = null

    override fun process(postcard: Postcard?, callback: InterceptorCallback?) {
        if(postcard == null){
            callback?.onContinue(postcard)
            return
        }
//        "=============== ${postcard.extra}\t${RouteExtras.CHECK_LOGIN} \t ${LoginServiceWrap.isLogin()}".loge()
        //判断是否需要登陆，如果需要则判断是否已经登陆
        if(postcard.extra and RouteExtras.CHECK_LOGIN == RouteExtras.CHECK_LOGIN && !LoginServiceWrap.isLogin()){
            EventBus.getDefault().register(this)
            p = postcard
            c = callback
            LoginServiceWrap.startLogin()
        }else{
            callback?.onContinue(postcard)
        }
    }

    override fun init(context: Context?) {

    }

    @Subscribe
    fun onLoginSuccessEvent(event:LoginSuccessEvent){
        c?.onContinue(p)
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    fun onLoginFailEvent(event:LoginFailEvent){
        c?.onInterrupt(Throwable("登陆失败"))
        EventBus.getDefault().unregister(this)
    }
}